package org.red_cross_service.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import jakarta.servlet.http.HttpServletResponse;
import org.red_cross_service.common.response.Response;
import org.red_cross_service.domain.dto.TrainingInfo;
import org.red_cross_service.domain.entity.ActivityEntity;
import org.red_cross_service.domain.entity.SignEntity;
import org.red_cross_service.domain.entity.UserEntity;
import org.red_cross_service.domain.vo.SignVO;
import org.red_cross_service.mapper.ActivityMapper;
import org.red_cross_service.mapper.SignMapper;
import org.red_cross_service.mapper.UserMapper;
import org.red_cross_service.utils.EasyExcelUtils;
import org.red_cross_service.utils.QueryWrapperUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.IOException;
import java.text.MessageFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
* @author zxs
* @description 针对表【rc_sign】的数据库操作Service实现
* @since 2025-06-07 10:16:52
*/
@Service
public class SignService  {

    @Autowired
    ActivityMapper activityMapper;

    @Autowired
    SignMapper signMapper;

    @Autowired
    private UserMapper userMapper;

    @Transactional(rollbackFor = Exception.class)
    public Response addSign(SignEntity signEntity) {
        ActivityEntity activityEntity = activityMapper.selectById(signEntity.getActivityId());
        if(activityEntity==null)
            return Response.error("活动不存在");
        SignEntity oldSign = signMapper.selectOne(
                new QueryWrapper<SignEntity>()
                        .eq("activity_id", signEntity.getActivityId())
                        .eq("sign_id_card", signEntity.getSignIdCard())
        );
        if(oldSign !=null)
            return Response.error("已报名");
        signMapper.insert(signEntity);
        activityMapper.updateById(activityEntity.setEnrollment(activityEntity.getEnrollment() + 1));
        return Response.success("报名成功");

    }

    public List<SignVO> getSignList(SignEntity signEntity ) {
        List<SignEntity> signEntityList = signMapper.selectList(
                QueryWrapperUtils.buildQuery(signEntity)
        );
        if(signEntityList.isEmpty()){
            return new ArrayList<>();
        }

        List<UserEntity> userEntityList = userMapper.selectBatchIds(signEntityList.stream().map(SignEntity::getUserId).toList());
        Map<Integer, UserEntity> userMap = userEntityList.stream().collect(Collectors.toMap(UserEntity::getUserId, o -> o));
        ArrayList<SignVO> signVOList = new ArrayList<>();
        List<Long> idList = signEntityList.stream().map(SignEntity::getActivityId).toList();
        Map<Long, String> activityMap = activityMapper.selectBatchIds(
                idList
        ).stream().collect(Collectors.toMap(ActivityEntity::getActivityId, ActivityEntity::getActivityName));
        for(SignEntity sign : signEntityList)
        {
            SignVO signVO = new SignVO();
            BeanUtils.copyProperties(sign,signVO);
            signVO.setActivityName(activityMap.getOrDefault(signVO.getActivityId(),""));
            // long 转integer
            signVO.setUser(userMap.getOrDefault(signVO.getUserId().intValue(),new UserEntity()));
            signVOList.add(signVO);
        }

        if(signEntity.getActivityName()==null && signEntity.getUnit()==null  ){
            return signVOList;
        }

        //根据查询条件返回结果
        return signVOList.stream().filter(o->
                        ( signEntity.getActivityName() == null || signEntity.getActivityName().isEmpty()  || o.getActivityName().contains(signEntity.getActivityName()) )
                        &&
                        ( signEntity.getUnit()==null ||  signEntity.getUnit().isEmpty() ||  o.getUser().getUnit().contains(signEntity.getUnit()) )
        ).toList();
    }

    public Response deleteSign(Long signId) {
        if(signMapper.deleteById(signId)>0){
            return Response.success();
        }
        else return Response.error("删除失败");

    }

    public Response updateSign(SignEntity signEntity) {
        return Response.success(signMapper.updateById(signEntity));
    }

    public Response selectOne(SignEntity signEntity) {
        return Response.success(signMapper.selectOne(
                QueryWrapperUtils.buildQuery(signEntity)
        ));
    }

    public Response selectUserTraining(Integer userId) {
        return Response.success(signMapper.selectList(
                new QueryWrapper<SignEntity>()
                        .eq("user_id",userId)
        ));
    }

    public Response selectUserList(Integer userId, Integer type) {
        List<SignEntity> signEntityList = signMapper.selectList(
                new QueryWrapper<SignEntity>()
                        .eq("user_id", userId)
        );
        if(signEntityList.isEmpty()){
            return Response.success();
        }
        List<Long> idList = signEntityList.stream().map(SignEntity::getActivityId).toList();
        Map<Long, ActivityEntity> activityMap = activityMapper.selectBatchIds(
                idList
        ).stream().collect(Collectors.toMap(ActivityEntity::getActivityId, o->o));
        ObjectMapper objectMapper = new ObjectMapper();
        ArrayList<SignEntity> type1 = new ArrayList<>();
        ArrayList<SignEntity> type2 = new ArrayList<>();
        for (SignEntity signEntity : signEntityList) {

            try {
                TrainingInfo trainingInfo = objectMapper.readValue(signEntity.getTrainingInfo(), TrainingInfo.class);
                Date now = new Date();
                SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                Date StartDate = simpleDateFormat.parse(trainingInfo.getStartDate());
                if(now.before(StartDate)){
                    type1.add(signEntity);
                }
                else type2.add(signEntity);
            } catch (JsonProcessingException | ParseException e) {
                throw new RuntimeException(e);
            }
        }
        if(type==0) {
            for(SignEntity signEntity : type1){
                signEntity.setActivityName(activityMap.get(signEntity.getActivityId()).getActivityName());
                signEntity.setActivityImg(activityMap.get(signEntity.getActivityId()).getActivityImg());
                signEntity.setEnrollment(activityMap.get(signEntity.getActivityId()).getEnrollment());
            }
            return Response.success(type1);
        }
        else if(type==1) {
            for(SignEntity signEntity : type2){
                signEntity.setActivityName(activityMap.get(signEntity.getActivityId()).getActivityName());
                signEntity.setActivityImg(activityMap.get(signEntity.getActivityId()).getActivityImg());
                signEntity.setEnrollment(activityMap.getOrDefault(signEntity.getActivityId(),new ActivityEntity().setEnrollment(0)).getEnrollment());
            }
            return Response.success(type2);
        }
        return Response.error("参数错误");
    }

    public void exportSignList(HttpServletResponse response, SignEntity signEntity) {
        List<SignVO> signList = getSignList(signEntity);
        ObjectMapper objectMapper = new ObjectMapper();
        try {
            signList.forEach(signVO -> {
                try {
                    TrainingInfo trainingInfo = objectMapper.readValue(signVO.getTrainingInfo(), TrainingInfo.class);
                    BeanUtils.copyProperties(trainingInfo,signVO);
                    signVO.setUnit(signVO.getUser().getUnit());
                } catch (JsonProcessingException e) {
                    throw new RuntimeException(e);
                }
            });
            EasyExcelUtils.writeWeb(response, signList, SignVO.class, "培训列表", "培训列表");
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}




